package gov.child.dao.impl;

import gov.child.dao.AbstractDao;
import gov.child.dao.UserDao;
import gov.child.dao.exception.EntityQueryException;
import gov.child.dao.exception.PageInitialException;
import gov.child.entities.po.EUser;
import gov.child.entities.vo.Page;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author fzh
 * @since 2017/9/10
 */
@Repository("userDao")
public class UserDaoImpl extends AbstractDao implements UserDao {

    @Override
    public List findAll(Page page) {
        Session session = currentSession();
        String hql = "from EUser ";
        Query query = session.createQuery(hql);
        return doPaginate(query, page);
    }

    @Override
    public EUser findByUsernameAndPassword(String username, String password) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EUser where username = :un and password = :pw";
        Query query = session.createQuery(hql)
                .setParameter("un", username)
                .setParameter("pw", password);
        return (EUser) query.uniqueResult();
    }

    @Override
    public EUser findByPhoneAndPassword(String phone, String password) throws EntityQueryException {
        Session session = currentSession();
        String hql = "from EUser where phone = :phone and password = :pw";
        Query query = session.createQuery(hql)
                .setParameter("phone", phone)
                .setParameter("pw", password);
        return (EUser) query.uniqueResult();
    }

    @Override
    public EUser findByIDNumAndPassword(String idNum, String password) throws EntityQueryException {
        Session session = currentSession();
        try {
            String hql = "from EUser where idNum = :ID and password = :pw";
            Query query = session.createQuery(hql)
                    .setParameter("ID", idNum)
                    .setParameter("pw", password);
            return (EUser) query.uniqueResult();
        } catch (HibernateException e) {
            throw new EntityQueryException("", e);
        }
    }

    @Override
    public void save(EUser user) {
        currentSession().save(user);
    }

    @Override
    public void delete(EUser user) {
        currentSession().delete(user);
    }

    @Override
    public void update(EUser user) {
        // TODO maybe need optimization
        currentSession().update(user);
    }

    @Override
    public Long total() throws PageInitialException {
        Session session = currentSession();
        String hql = "select count(*) from EUser ";
        return (Long) session.createQuery(hql).uniqueResult();
    }
}
